package net.loodies;




import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;

public class AsyncResourceLoader extends Thread {

	protected static final String TAG = "AsyncResourceLoader";
	
	
	LoodiesErrorListener mErrorCB = null;
	Hashtable<String, String> map = null;
	String mUrlString;
	String mJSONString;
	String loodieType = "";
	ArrayList<String> arrayListBitmapNames;
	Hashtable<String, String> mapBitmapNames;
	
	AsyncResourceLoaderCallback mCallback;
	DisplayMetrics mDisplayMetrics;
	
	private int BANNER_EXPECTED_WIDTH = 320;
	private int BANNER_EXPECTED_HEIGHT = 50;
	
	static public Hashtable<String, Bitmap> mapBitmap = new Hashtable<String, Bitmap>();

	Hashtable<String, String> getMap() {
		return map;
	}

	Bitmap getBitmap(int index) {
		String bitmapName = arrayListBitmapNames.get(index);
		return mapBitmap.get(bitmapName);
	}

	public AsyncResourceLoader( AsyncResourceLoaderCallback callback,
								String url,
								LoodiesErrorListener loodiesErrorCallback,
								DisplayMetrics displayMetrics) {
		
		mErrorCB = loodiesErrorCallback;
		mCallback = callback;
		mUrlString = url;
		arrayListBitmapNames = new ArrayList<String>();
		mapBitmapNames = new Hashtable<String, String>();
		mDisplayMetrics = displayMetrics;
		start();

	}

	public void run() {
		Resource resource = new Resource();
		
		try {
			Log.v(TAG, "loading loadJSON("+mUrlString +")");
			mJSONString = Utils.loadJSON(mUrlString);
		} catch (Exception e) {
			Utils.ASSERT_AND_ERROR(true, "Cant load JSON at" + mUrlString, mErrorCB);
			e.printStackTrace();
		}
		
		try {
			map = Utils.parse(mJSONString);
		} catch (Exception e) {
			Utils.ASSERT_AND_ERROR(true, "Cant parse JSON :" + mJSONString, mErrorCB);
			e.printStackTrace();
		}

		if (map != null) {
			resource.mType = map.get("type");
			resource.mUrlNotification = map.get("click_notification_url");
			resource.mUrlDestination = map.get("ad_destination_url");
			resource.mUrlImage = map.get("ad_object_url");
			Log.v(TAG, "mType"+resource.mType);
			Log.v(TAG, "mUrlNotification"+resource.mUrlNotification);
			Log.v(TAG, "mUrlDestination"+resource.mUrlDestination);
		
			String urlstrContainer = map.get("container_url");
			String urlstr = map.get("ad_object_url");
			String urlstrClose = map.get("close_url");

			String urlMessageBanner = map.get("message_url");
			resource.mMessageAnchor = (urlMessageBanner!=null)?urlMessageBanner:"";
			Log.v(TAG, "urlstrContainer"+urlstrContainer);
			Log.v(TAG, "urlstr"+urlstr);
			Log.v(TAG, "urlstrClose"+urlstrClose);
			Log.v(TAG, "urlMessageBanner"+urlMessageBanner);
				
			if (urlstr != null) {
				arrayListBitmapNames.add(urlstr);
				mapBitmapNames.put( urlstr,"ad");
			}
			if (urlstrContainer != null) {
				arrayListBitmapNames.add(urlstrContainer);
				mapBitmapNames.put( urlstrContainer,"container");
			}
			if (urlstrClose != null) {
				arrayListBitmapNames.add(urlstrClose);
				mapBitmapNames.put( urlstrClose,"close");
				
			}
			if (urlMessageBanner != null) {
				resource.mbHasAnchorBitmap = true;
				arrayListBitmapNames.add(urlMessageBanner);
				mapBitmapNames.put( urlMessageBanner,"anchor");
			}
			try {
				for (int i = 0; i < arrayListBitmapNames.size(); i++) {
					String url = arrayListBitmapNames.get(i);
					String key = mapBitmapNames.get(url);
					if (url != null) {
				
						URL bitmapUrl = null;
						try {
							bitmapUrl = new URL(url);
						} catch (MalformedURLException e) {
							
							Utils.ASSERT_AND_ERROR(false, "bad bitmap url"+ bitmapUrl, mErrorCB);
							
							
							e.printStackTrace();
						}
						HttpGet httpRequest = null;

						try {
							httpRequest = new HttpGet(bitmapUrl.toURI());
						} catch (URISyntaxException e) {
						
							Utils.ASSERT_AND_ERROR(false, "HttpGet(bitmapUrl.toURI()) failed"+ bitmapUrl, mErrorCB);
								
							e.printStackTrace();
						}

						HttpClient httpclient = new DefaultHttpClient();
						HttpResponse response = null;
						try {
							response = (HttpResponse) httpclient
									.execute(httpRequest);
						} catch (ClientProtocolException e) {
							Utils.ASSERT_AND_ERROR(false, "httpclient.execute(httpRequest) failed"+ bitmapUrl, mErrorCB);
							
							

							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							continue;
						}

						HttpEntity entity = response.getEntity();
						BufferedHttpEntity bufHttpEntity = null;
						try {
							bufHttpEntity = new BufferedHttpEntity(entity);
						} catch (IOException e) {
							Utils.ASSERT_AND_ERROR(false, "BufferedHttpEntity failed"+ bitmapUrl, mErrorCB);
							e.printStackTrace();
						}
						try {
							InputStream instream = bufHttpEntity.getContent();
							Bitmap _bitmap = BitmapFactory.decodeStream(instream);
							
								resource.mFixedBitmap = _bitmap;
					
								// TODO si on loade la banniere 320x50
								if(resource.mType.contains("fixed")&&key.contains("ad")){
									if(_bitmap.getWidth()==BANNER_EXPECTED_WIDTH&&_bitmap.getHeight()==BANNER_EXPECTED_HEIGHT){
										int widthPixels  = mDisplayMetrics.widthPixels;
										float ratio = (float)BANNER_EXPECTED_HEIGHT / (float)BANNER_EXPECTED_WIDTH;
										int heightPixels = (int) (widthPixels*ratio);
										Bitmap scaledBitmap = Bitmap.createScaledBitmap(_bitmap, widthPixels,heightPixels,false);
										resource.mBitmaps.add(scaledBitmap);
										resource.mMapBitmapNames.put( key,scaledBitmap);
										
										//urlMessageBanner
									}
									
								}
								else{
									resource.mBitmaps.add(_bitmap);
									resource.mMapBitmapNames.put( key,_bitmap);
											
								}
								
							
							
						} catch (IOException e) {
							Utils.ASSERT_AND_ERROR(false, "BitmapFactory.decodeStream(instream)"+ bitmapUrl, mErrorCB);
							e.printStackTrace();
						}
					}

				}
			} catch (Exception e) {
				Utils.ASSERT_AND_ERROR(false, "Failed to load bitmap", mErrorCB);
				e.printStackTrace();
			}
			mCallback.onFinishLoading(resource);
		}
	}

	public void Shutdown() {
		// TODO Auto-generated method stub
		Log.v(TAG,"Shutdown()");
	}
}
